package org.dreamwork.jasmine2.web.controls.chart.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2010-5-12
 * Time: 11:31:37
 */
public class FlashChartAsynchronousServlet extends HttpServlet {
    @Override
    protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fileName = request.getParameter ("f");
        ServletContext ctx = getServletContext ();
        File path = (File) ctx.getAttribute ("javax.servlet.context.tempdir");
        File file = new File (path, fileName);
        if (!file.exists ()) {
            response.sendError (404);
            return;
        }

        InputStream in = new FileInputStream (file);
        try {
            byte[] buff = new byte[(int) file.length ()];
            response.setContentType ("text/xml");
            int length = in.read (buff);
            response.getOutputStream ().write (buff, 0, length);
            response.flushBuffer ();
        } finally {
            in.close ();
//            file.delete ();
        }
    }
}